package cn.neusoft.service.impl;

import cn.neusoft.bean.Food;
import cn.neusoft.bean.User;
import cn.neusoft.dao.IUserDao;
import cn.neusoft.dao.impl.UserDao;
import cn.neusoft.query.BaseQuery;
import cn.neusoft.service.IUserService;
import cn.neusoft.vo.PageBean;
import cn.neusoft.vo.ResultBean;
import com.alibaba.druid.util.StringUtils;

import java.util.List;

public class UserService implements IUserService {
    private IUserDao userDao;
    public  UserService(){
        userDao=new UserDao();
    }
    @Override
    public ResultBean add(User user) throws Exception {
        if(user==null
        ||StringUtils.isEmpty(user.getUserName())){
       return ResultBean.ERROR(10001,"params null");
        }
        int i=userDao.add(user);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("add user fail");
    }

    @Override
    public ResultBean update(User user) throws Exception {
        if(user==null|| user.getUserId()==null){
            return ResultBean.ERROR("params null");
        }
        int i=userDao.update(user);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("update user fail");
    }

    @Override
    public ResultBean delete(Integer id) throws Exception {
if (id==null){
    return ResultBean.ERROR("params null");
}
int i=userDao.delete(id);
return i>0?ResultBean.SUCCESS():ResultBean.ERROR("delete user fail");
    }

    @Override
    public ResultBean getById(Integer id) throws Exception {
        if (id==null){
            return ResultBean.ERROR("params null");
        }
        User user=userDao.getById(id);
        return user!=null?ResultBean.SUCCESS(user):ResultBean.ERROR("select food by id fail");
    }

    @Override
    public ResultBean getAll() throws Exception {
        List<User> userList=userDao.getAll();
        return userList!=null?ResultBean.SUCCESS():ResultBean.ERROR("select food by id fail");
    }

    @Override
    public ResultBean getByPage(BaseQuery baseQuery) throws Exception {
        PageBean<User> pageBean = new PageBean<>();
       int count=userDao.getCount(baseQuery);
       pageBean.setTotalRows(count);
        if(count% baseQuery.getPageCount()==0){
            pageBean.setTotalPages(count/baseQuery.getPageCount());
        }else{
            pageBean.setTotalPages(count/baseQuery.getPageCount()+1);
        }

        List<User> userList=userDao.getByPage(baseQuery);
        pageBean.setData(userList);

        return ResultBean.SUCCESS(pageBean);

    }

    @Override
    public ResultBean batchDel(List<Integer> ids) throws Exception {
        if (ids==null||ids.size()==0){
            return ResultBean.ERROR("params null");
        }
        for (Integer id:ids){
            userDao.delete(id);
        }


        return ResultBean.SUCCESS();
    }
}
